package com.jyy.prefabricated.service.impl;

import com.jyy.prefabricated.entity.Student;
import com.jyy.prefabricated.entity.ViewLog;
import com.jyy.prefabricated.mapper.StudentMapper;
import com.jyy.prefabricated.mapper.ViewLogMapper;
import com.jyy.prefabricated.service.ViewLogService;
import net.polyv.vod.v1.entity.datastatistics.VodQueryViewLogByDayRequest;
import net.polyv.vod.v1.entity.datastatistics.VodQueryViewLogByDayResponse;
import net.polyv.vod.v1.service.datastatistics.impl.VodDataStatisticsServiceImpl;
import org.junit.Assert;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * 视频日志表(ViewLog)表服务实现类
 *
 * @author mrl
 * @since 2021-10-15 10:51:42
 */
@Service("viewLogService")
public class ViewLogServiceImpl implements ViewLogService {
    @Resource
    private ViewLogMapper viewLogDao;

    @Resource
    private StudentMapper studentMapper;
    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public ViewLog queryById(Integer id) {
        return this.viewLogDao.queryById(id);
    }

    @Override
    public void viewLog()  throws IOException, NoSuchAlgorithmException {
        Calendar ca = Calendar.getInstance();
        ca.setTime(new Date());
        ca.add(Calendar.DATE, -1);
        Date lastDay = ca.getTime();
        VodQueryViewLogByDayRequest vodQueryViewLogByDayRequest = new VodQueryViewLogByDayRequest();
        List<VodQueryViewLogByDayResponse> vodQueryViewLogByDayResponseList = null;
        vodQueryViewLogByDayRequest.setDay(lastDay)
                .setVideoId(null)
                .setCategoryId(null)
                .setSessionId(null)
                .setViewerId(null);
        vodQueryViewLogByDayResponseList = new VodDataStatisticsServiceImpl().queryViewLogByDay(
                vodQueryViewLogByDayRequest);
        Assert.assertNotNull(vodQueryViewLogByDayResponseList);
        Map<String, Map> map = new HashMap<>();
        for (VodQueryViewLogByDayResponse vodQueryViewLogByDayResponse:vodQueryViewLogByDayResponseList) {
            if(vodQueryViewLogByDayResponse.getSessionId() != null && !"".equals(vodQueryViewLogByDayResponse.getSessionId()) && vodQueryViewLogByDayResponse.getVideoId() != null && !"".equals(vodQueryViewLogByDayResponse.getVideoId())){
                /**
                 * 观众id_视频id作为键 总时长 进度条时间 视频时长做为值 map已存在累加时长 不存在放入map
                 */
                boolean sfcz = map.containsKey(vodQueryViewLogByDayResponse.getSessionId()+"_"+vodQueryViewLogByDayResponse.getVideoId());
                if(sfcz){
                    Map old = map.get(vodQueryViewLogByDayResponse.getSessionId()+"_"+vodQueryViewLogByDayResponse.getVideoId());
                    Integer playDuration = (Integer) old.get("playDuration");
                    Map<String, Integer> newValue = new HashMap<>();
                    newValue.put("playDuration",vodQueryViewLogByDayResponse.getPlayDuration()+playDuration);
                    /**
                     *  如果观众当天观看的最后一次日志 是在最后面不用改 如果观众当天观看的最后一次日志是在最前面 此处值改为old.get("currentTimes")
                     */
                    newValue.put("currentTimes",vodQueryViewLogByDayResponse.getCurrentTimes());
                    newValue.put("duration",vodQueryViewLogByDayResponse.getDuration());
                    map.put(vodQueryViewLogByDayResponse.getSessionId()+"_"+vodQueryViewLogByDayResponse.getVideoId(),newValue);
                }else{
                    /**
                     * 查询是否是本系统观众日志
                     */
                    Student student = studentMapper.selectByPrimaryKey(Integer.valueOf(vodQueryViewLogByDayResponse.getSessionId()));
                    if(student != null){
                        /**
                         * 存入map
                         */
                        Map<String, Integer> value = new HashMap<>();
                        value.put("playDuration",vodQueryViewLogByDayResponse.getPlayDuration());
                        value.put("currentTimes",vodQueryViewLogByDayResponse.getCurrentTimes());
                        value.put("duration",vodQueryViewLogByDayResponse.getDuration());
                        map.put(vodQueryViewLogByDayResponse.getSessionId()+"_"+vodQueryViewLogByDayResponse.getVideoId(),value);
                    }

                }
            }
        }
        if(map != null){
            for (Map.Entry<String, Map> entry : map.entrySet()) {
                ViewLog viewLog = new ViewLog();
                String[] keys = entry.getKey().split("_");
                viewLog.setSessionId(keys[0]);
                viewLog.setVideoId(keys[1]);
                Map value = entry.getValue();
                Integer playDuration = (Integer) value.get("playDuration");
                Integer currentTimes = (Integer) value.get("currentTimes");
                Integer duration = (Integer) value.get("duration");
                List<ViewLog> viewLogList = viewLogDao.queryAll(viewLog);
                if(viewLogList != null && viewLogList.size() > 0){
                    ViewLog updateLog = new ViewLog();
                    updateLog.setId(viewLogList.get(0).getId());
                    updateLog.setPlayDuration(playDuration+viewLogList.get(0).getPlayDuration());
                    updateLog.setCurrentTimes(currentTimes.toString());
                    updateLog.setCreateTime(new Date());
                    viewLogDao.update(updateLog);
                }else{
                    viewLog.setPlayDuration(playDuration);
                    viewLog.setCurrentTimes(currentTimes.toString());
                    viewLog.setDuration(duration.toString());
                    viewLog.setCreateTime(new Date());
                    viewLogDao.insert(viewLog);
                }

            }
        }
    }
    @Override
    public void nowViewLog() throws IOException, NoSuchAlgorithmException {
        Calendar ca = Calendar.getInstance();
        ca.setTime(new Date());
//        ca.add(Calendar.DATE, -1);
        Date lastDay = ca.getTime();
        VodQueryViewLogByDayRequest vodQueryViewLogByDayRequest = new VodQueryViewLogByDayRequest();
        List<VodQueryViewLogByDayResponse> vodQueryViewLogByDayResponseList = null;
        vodQueryViewLogByDayRequest.setDay(lastDay)
                .setVideoId(null)
                .setCategoryId(null)
                .setSessionId(null)
                .setViewerId(null);
        vodQueryViewLogByDayResponseList = new VodDataStatisticsServiceImpl().queryViewLogByDay(
                vodQueryViewLogByDayRequest);
        Assert.assertNotNull(vodQueryViewLogByDayResponseList);
        Map<String, Map> map = new HashMap<>();
        for (VodQueryViewLogByDayResponse vodQueryViewLogByDayResponse:vodQueryViewLogByDayResponseList) {
            if(vodQueryViewLogByDayResponse.getSessionId() != null && !"".equals(vodQueryViewLogByDayResponse.getSessionId()) && vodQueryViewLogByDayResponse.getVideoId() != null && !"".equals(vodQueryViewLogByDayResponse.getVideoId())){
                /**
                 * 观众id_视频id作为键 总时长 进度条时间 视频时长做为值 map已存在累加时长 不存在放入map
                 */
                boolean sfcz = map.containsKey(vodQueryViewLogByDayResponse.getSessionId()+"_"+vodQueryViewLogByDayResponse.getVideoId());
                if(sfcz){
                    Map old = map.get(vodQueryViewLogByDayResponse.getSessionId()+"_"+vodQueryViewLogByDayResponse.getVideoId());
                    Integer playDuration = (Integer) old.get("playDuration");
                    Map<String, Integer> newValue = new HashMap<>();
                    newValue.put("playDuration",vodQueryViewLogByDayResponse.getPlayDuration()+playDuration);
                    /**
                     *  如果观众当天观看的最后一次日志 是在最后面不用改 如果观众当天观看的最后一次日志是在最前面 此处值改为old.get("currentTimes")
                     */
                    newValue.put("currentTimes",vodQueryViewLogByDayResponse.getCurrentTimes());
                    newValue.put("duration",vodQueryViewLogByDayResponse.getDuration());
                    map.put(vodQueryViewLogByDayResponse.getSessionId()+"_"+vodQueryViewLogByDayResponse.getVideoId(),newValue);
                }else{
                    /**
                     * 查询是否是本系统观众日志
                     */
                    Student student = studentMapper.selectByPrimaryKey(Integer.valueOf(vodQueryViewLogByDayResponse.getSessionId()));
                    if(student != null){
                        /**
                         * 存入map
                         */
                        Map<String, Integer> value = new HashMap<>();
                        value.put("playDuration",vodQueryViewLogByDayResponse.getPlayDuration());
                        value.put("currentTimes",vodQueryViewLogByDayResponse.getCurrentTimes());
                        value.put("duration",vodQueryViewLogByDayResponse.getDuration());
                        map.put(vodQueryViewLogByDayResponse.getSessionId()+"_"+vodQueryViewLogByDayResponse.getVideoId(),value);
                    }

                }
            }
        }
        if(map != null){
            for (Map.Entry<String, Map> entry : map.entrySet()) {
                ViewLog viewLog = new ViewLog();
                String[] keys = entry.getKey().split("_");
                viewLog.setSessionId(keys[0]);
                viewLog.setVideoId(keys[1]);
                Map value = entry.getValue();
                Integer playDuration = (Integer) value.get("playDuration");
                Integer currentTimes = (Integer) value.get("currentTimes");
                Integer duration = (Integer) value.get("duration");
                List<ViewLog> viewLogList = viewLogDao.queryAll(viewLog);
                if(viewLogList != null && viewLogList.size() > 0){
                    ViewLog updateLog = new ViewLog();
                    updateLog.setId(viewLogList.get(0).getId());
                    updateLog.setPlayDuration(playDuration+viewLogList.get(0).getPlayDuration());
                    updateLog.setCurrentTimes(currentTimes.toString());
                    updateLog.setCreateTime(new Date());
                    viewLogDao.update(updateLog);
                }else{
                    viewLog.setPlayDuration(playDuration);
                    viewLog.setCurrentTimes(currentTimes.toString());
                    viewLog.setDuration(duration.toString());
                    viewLog.setCreateTime(new Date());
                    viewLogDao.insert(viewLog);
                }

            }
        }
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<ViewLog> queryAllByLimit(int offset, int limit) {
        return this.viewLogDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param viewLog 实例对象
     * @return 实例对象
     */
    @Override
    public ViewLog insert(ViewLog viewLog) {
        ViewLog queryLog = new ViewLog();
        queryLog.setSessionId(viewLog.getSessionId());
        queryLog.setVideoId(viewLog.getVideoId());
        List<ViewLog> viewLogList = viewLogDao.queryAll(queryLog);
        if(viewLogList != null && viewLogList.size() > 0){
            ViewLog updateLog = new ViewLog();
            updateLog.setId(viewLogList.get(0).getId());
            updateLog.setPlayDuration(viewLog.getPlayDuration()+viewLogList.get(0).getPlayDuration());
            updateLog.setCurrentTimes(viewLog.getCurrentTimes());
            updateLog.setCreateTime(new Date());
            viewLogDao.update(updateLog);
            return updateLog;
        }else{
            viewLog.setCreateTime(new Date());
            viewLogDao.insert(viewLog);

            return viewLog;
        }
    }

    /**
     * 修改数据
     *
     * @param viewLog 实例对象
     * @return 实例对象
     */
    @Override
    public ViewLog update(ViewLog viewLog) {
        this.viewLogDao.update(viewLog);
        return this.queryById(viewLog.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.viewLogDao.deleteById(id) > 0;
    }
}